package com.ehome.poct.core.service.order;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.ehome.clinic.api.MarketingActivityClient;
import com.ehome.context.thread.UserThreadLocal;
import com.ehome.core.service.AbstractCrudServiceImpl;
import com.ehome.core.util.BeanConvertUtil;
import com.ehome.exception.BizException;
import com.ehome.poct.base.api.dto.doctor.ClinicDTO;
import com.ehome.poct.base.api.enums.StripTypeEnums;
import com.ehome.poct.core.api.common.DomainBizCode;
import com.ehome.poct.core.api.dto.PriceProfitResultDTO;
import com.ehome.poct.core.api.dto.check.TestReportDataConfigDTO;
import com.ehome.poct.core.api.dto.check.gold.TestConfPoctStripTypeDTO;
import com.ehome.poct.core.api.dto.order.PromotionBundlePriceProfitConfDTO;
import com.ehome.poct.core.api.dto.order.TestStripPriceProfitDTO;
import com.ehome.poct.core.api.dto.order.TestStripPriceProfitSchemeDTO;
import com.ehome.poct.core.api.dto.order.TestStripPriceProfitSchemeOperateRecordDTO;
import com.ehome.poct.core.api.dto.report.PriceProfitDTO;
import com.ehome.poct.core.api.dto.report.ProfitDTO;
import com.ehome.poct.core.api.qry.StripPriceProfitQry;
import com.ehome.poct.core.api.virtual.PromotionBundlePriceProfitConfService;
import com.ehome.poct.core.api.virtual.TestStripPriceProfitSchemeOperateRecordService;
import com.ehome.poct.core.api.virtual.TestStripPriceProfitSchemeService;
import com.ehome.poct.core.api.virtual.TestStripPriceProfitService;
import com.ehome.poct.core.repository.TestConfPoctStripTypeRepository;
import com.ehome.poct.core.repository.TestReportDataConfigRepository;
import com.ehome.poct.core.repository.order.TestStripPriceProfitRepository;
import com.ehome.poct.core.repository.order.TestStripPriceProfitSchemeRepository;
import com.ehome.poct.core.service.mapping.TestStripPriceProfitMapping;
import com.ehome.poct.core.service.rpc.ClinicClient;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 检测价格方案表新增地总也需要copy一份选定的省总价格方案SerivceImlp
 *
 * @author ehome
 * @Date 2022-06-29 14:57
 */
@Service
@Slf4j
public class TestStripPriceProfitSchemeServiceImpl extends AbstractCrudServiceImpl<TestStripPriceProfitSchemeDTO> implements TestStripPriceProfitSchemeService {

    @Autowired
    TestStripPriceProfitSchemeService testStripPriceProfitSchemeService;
    @Autowired
    PromotionBundlePriceProfitConfService promotionBundlePriceProfitConfService;
    @Autowired
    TestStripPriceProfitService testStripPriceProfitService;
    @Autowired
    TestStripPriceProfitMapping testStripPriceProfitMapping;
    @Autowired
    TestStripPriceProfitSchemeOperateRecordService testStripPriceProfitSchemeOperateRecordService;
    @Autowired
    TestStripPriceProfitSchemeRepository testStripPriceProfitSchemeRepository;
    @Autowired
    TestStripPriceProfitRepository testStripPriceProfitRepository;
    @Autowired
    ClinicClient clinicClient;
    @Autowired
    MarketingActivityClient marketingActivityClient;
    @Autowired
    TestConfPoctStripTypeRepository testConfPoctStripTypeRepository;
    @Autowired
    TestReportDataConfigRepository testReportDataConfigRepository;

    //肺支肺衣联合检测
    private final Map<Integer, String> U_MPIGM_CPNIGM_REPORT = Map.ofEntries(Map.entry(6, "MPIGM_REPORT")
            , Map.entry(17, "CPNIGM_REPORT")
            , Map.entry(50, "U_MPIGM_CPNIGM_REPORT"));
    //肺支总抗肺衣联合检测
    private final Map<Integer, String> U_MP_AB_CPNIGM_REPORT = Map.ofEntries(Map.entry(9, "MPAB_REPORT")
            , Map.entry(17, "CPNIGM_REPORT")
            , Map.entry(51, "U_MP_AB_CPNIGM_REPORT"));

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PriceProfitResultDTO addProfit(PriceProfitDTO dto) {
        log.info("新增价格方案 参数 ={}",dto);
        PriceProfitResultDTO result = new PriceProfitResultDTO();
        //校验数据是否齐全
        checkData(dto.getProfitList());
        if (dto.getTestStripPriceProfitSchemeId() == null) {
            var profitSchemeDTO = testStripPriceProfitSchemeService.insert(createTestStripPriceProfitSchemeDTO(dto.getPriceProfitSchemeName(),dto.getIsActivity()));
            result.setStripPriceProfitSchemeId(profitSchemeDTO.getTestStripPriceProfitSchemeId().toString());
            List<String> ids = Lists.newArrayList();
            dto.getProfitList().forEach(r -> {
                //捆绑促销活动
                bundlePriceProfitConf(r, dto.setTestStripPriceProfitSchemeId(profitSchemeDTO.getTestStripPriceProfitSchemeId()));
                TestStripPriceProfitDTO profitDTO = testStripPriceProfitService.insert(createTestStripPriceProfitDTO(profitSchemeDTO.getTestStripPriceProfitSchemeId(), r));
                ids.add(profitDTO.getTestStripPriceProfitId().toString());
            });
            result.setStripPriceProfitIds(ids);
            //保存操作记录
            saveRecord("新增", profitSchemeDTO.getTestStripPriceProfitSchemeId(), dto.getPriceProfitSchemeName());
        } else {
            //校验是否存在相同的价格方案
            TestStripPriceProfitSchemeDTO tspps = new TestStripPriceProfitSchemeDTO();
            tspps.setPriceProfitSchemeName(dto.getPriceProfitSchemeName());
            final var testStripPriceProfitSchemeDTO = testStripPriceProfitSchemeService.list(tspps).stream().findFirst().orElse(null);
            if (testStripPriceProfitSchemeDTO != null && !testStripPriceProfitSchemeDTO.getTestStripPriceProfitSchemeId().equals(dto.getTestStripPriceProfitSchemeId())) {
                throw new BizException(DomainBizCode.PRICE_SCHEME_NAME_ALREADY_EXISTS);
            }
            testStripPriceProfitSchemeService.update(dto.getTestStripPriceProfitSchemeId(), new TestStripPriceProfitSchemeDTO().setPriceProfitSchemeName(dto.getPriceProfitSchemeName()));
            //删除原有价格项
            testStripPriceProfitService.deleteProfitById(dto.getTestStripPriceProfitSchemeId());
            //删除原有捆绑促销活动
            var priceConf = promotionBundlePriceProfitConfService.list(new PromotionBundlePriceProfitConfDTO().setTestStripPriceProfitSchemeId(dto.getTestStripPriceProfitSchemeId()));
            priceConf.forEach(p -> promotionBundlePriceProfitConfService.delete(p.getPromotionBundlePriceProfitConfId()));
            dto.getProfitList().forEach(r -> {
                //捆绑促销活动
                bundlePriceProfitConf(r, dto);
                testStripPriceProfitService.insert(createTestStripPriceProfitDTO(dto.getTestStripPriceProfitSchemeId(), r));
            });
            //保存操作记录
            saveRecord("编辑", dto.getTestStripPriceProfitSchemeId(), dto.getPriceProfitSchemeName());
        }
        return result;
    }

    @Override
    public PriceProfitDTO getInfoById(Long priceProfitSchemeId) {
        return this.getInfoById(priceProfitSchemeId, null);
    }

    private PriceProfitDTO getInfoById(Long priceProfitSchemeId, List<Integer> stripTypeCodes) {
        TestStripPriceProfitSchemeDTO schemeDTO = testStripPriceProfitSchemeRepository.getById(priceProfitSchemeId);
        if(schemeDTO != null){
            TestStripPriceProfitDTO f = new TestStripPriceProfitDTO();
            f.setTestStripPriceProfitSchemeId(schemeDTO.getTestStripPriceProfitSchemeId());
            if (CollUtil.isNotEmpty(stripTypeCodes)) {
                Map<String, Object> map = Maps.newHashMap();
                map.put("stripTypeCode", stripTypeCodes);
                f.setMap(map);
            }
            List<TestStripPriceProfitDTO> list = testStripPriceProfitRepository.list(f);


            PriceProfitDTO ppd = new PriceProfitDTO();
            ppd.setTestStripPriceProfitSchemeId(schemeDTO.getTestStripPriceProfitSchemeId());
            ppd.setPriceProfitSchemeName(schemeDTO.getPriceProfitSchemeName());

            List<ProfitDTO> profitList = BeanConvertUtil.convertBeanList(list, ProfitDTO.class);
            ppd.setProfitList(profitList);
            return ppd;
        }
        return null;
    }

    @Override
    public List<ProfitDTO> getProfitService(StripPriceProfitQry qry) {
        log.info("获取价格方案 参数: {}", qry);
        //1.根据诊所ID 获取对应的价格方案
        ClinicDTO clinic = clinicClient.getById(qry.getClinicId());
        if (clinic == null) {
            throw new BizException("诊所不能为空");
        }

        //特殊处理 617 和 917
        if (qry.getStripTypeCodes().contains(6) && qry.getStripTypeCodes().contains(17)) {
            qry.getStripTypeCodes().add(50);
        }
        if (qry.getStripTypeCodes().contains(9) && qry.getStripTypeCodes().contains(17)) {
            qry.getStripTypeCodes().add(51);
        }
        if (qry.getStripTypeCodes().contains(4) && qry.getStripTypeCodes().contains(5) && qry.getStripTypeCodes().contains(100) ) {
            qry.getStripTypeCodes().add(121);
        }

        Long testStripPriceProfitSchemeId = clinic.getTestStripPriceProfitSchemeId();
        PriceProfitDTO profitDTO = this.getInfoById(testStripPriceProfitSchemeId, qry.getStripTypeCodes());
        if(profitDTO == null){
            throw new BizException("诊所不存在价格方案");
        }
        List<ProfitDTO> profitList = profitDTO.getProfitList();

        if (CollUtil.isNotEmpty(profitList)) {
            //2.查询是否存在捆绑活动 根据捆绑活动处理价格方案
            List<PromotionBundlePriceProfitConfDTO> confList = this.getPromotionBundlePriceProfitConf(testStripPriceProfitSchemeId);
            if (CollUtil.isEmpty(confList)) {
                profitList = profitList.stream().filter(f -> f.getStripTypeCode() != 50 || f.getStripTypeCode() != 51).collect(Collectors.toList());
            }
            log.info("获取价格查询是否存在捆绑活动后方案 结果: {}", profitList);


            Map<String, List<PromotionBundlePriceProfitConfDTO>> profitConfMap = confList.stream()
                    .collect(Collectors.groupingBy(PromotionBundlePriceProfitConfDTO::getProductCombineCode));

            //3.获取诊所的检测活动 根据检测活动处理价格方案
            List<Long> marketList = marketingActivityClient.getActivityScheme(qry.getClinicId()).getData();
            log.info("获取诊所的检测活动 根据检测活动处理价格方案 结果ID: {}", marketList);
            if (CollUtil.isNotEmpty(marketList)) {
                List<ProfitDTO> marketProfitList = Lists.newArrayList();
                for (Long schemeId : marketList) {
                    PriceProfitDTO info = this.getInfoById(schemeId);
                    marketProfitList.addAll(info.getProfitList());
                }
                log.info("获取诊所的检测活动 根据检测活动处理价格方案 结果List: {}", marketProfitList);
                Map<Integer, ProfitDTO> profitMap = profitList.stream().collect(Collectors.toMap(ProfitDTO::getStripTypeCode, Function.identity(), (key1, key2) -> key1.getCreateTime().compareTo(key2.getCreateTime()) > 0?key1:key2));
                Map<Integer, ProfitDTO> marketProfitMap = marketProfitList.stream().filter(f -> qry.getStripTypeCodes().contains(f.getStripTypeCode())).collect(Collectors.toMap(ProfitDTO::getStripTypeCode, Function.identity(), (key1, key2) -> key1.getCreateTime().compareTo(key2.getCreateTime()) > 0?key1:key2));
                profitList = profitList.stream().map(m -> {
                    ProfitDTO marketProfit = marketProfitMap.get(m.getStripTypeCode());
                    return Objects.requireNonNullElse(marketProfit, m);
                }).collect(Collectors.toList());

                List<TestReportDataConfigDTO> dataConfigList = testReportDataConfigRepository.list();
                Set<String> productCodeSet = dataConfigList.stream()
                        .filter(dataConfDTO -> StrUtil.isNotBlank(dataConfDTO.getPromotionProductCode()))
                        .filter(dataConfDTO -> dataConfDTO.getReportType().equals(2))
                        .map(TestReportDataConfigDTO::getPromotionProductCode).collect(Collectors.toSet());

                Integer stripCode = getCombineCodeStripCode(profitConfMap, productCodeSet, StripTypeEnums.U_MPIGM_CPNIGM_REPORT.getReportTypeCode());
                if (qry.getStripTypeCodes().contains(6) && qry.getStripTypeCodes().contains(17) && marketProfitMap.get(50) != null && Objects.nonNull(stripCode)) {
                    profitList.add(marketProfitMap.get(50));
                }

                stripCode = getCombineCodeStripCode(profitConfMap, productCodeSet, StripTypeEnums.U_MP_AB_CPNIGM_REPORT.getReportTypeCode());
                if (qry.getStripTypeCodes().contains(9) && qry.getStripTypeCodes().contains(17) && marketProfitMap.get(51) != null && Objects.nonNull(stripCode)) {
                    profitList.add(marketProfitMap.get(51));
                }
                //获取只有活动存在的价格方案
                var subtractSet = CollUtil.subtract(marketProfitMap.keySet(),profitMap.keySet());
                if (CollUtil.isNotEmpty(subtractSet)) {
                    for (Integer f : subtractSet) {
                        profitList.add(marketProfitMap.get(f));
                    }
                }
            }

            //4.处理价格方案 特殊处理联测逻辑
            profitList = this.handleProfit(profitList,testStripPriceProfitSchemeId);

            //5.添加补充字段
            if (CollUtil.isNotEmpty(qry.getStripTypeCodes())) {
                profitList = setAuxiliaryField(qry.getStripTypeCodes(), profitList);
            }
        }

        log.info("获取价格方案 结果: {}", profitList);
        profitList.forEach(profit -> {
            if (Objects.isNull(profit.getYhProfits())) {
                profit.setYhProfits(BigDecimal.ZERO);
            }
        });
        return profitList;
    }

    /**
     * 获取组合报告的检查代码
     *
     * @param profitConfMap
     * @param productCodeSet
     * @param reportCode
     * @return
     */
    private Integer getCombineCodeStripCode(Map<String, List<PromotionBundlePriceProfitConfDTO>> profitConfMap, Set<String> productCodeSet, String reportCode) {
        if (MapUtil.isEmpty(profitConfMap)) {
            return null;
        }
        for (Map.Entry<String, List<PromotionBundlePriceProfitConfDTO>> entry : profitConfMap.entrySet()) {
            Optional<String> optional = productCodeSet.stream().filter(productCode -> StrUtil.equals(entry.getKey(), productCode)).findFirst();
            if (optional.isEmpty()) {
                continue;
            }
            List<PromotionBundlePriceProfitConfDTO> profitConfDTOList = entry.getValue();
            Optional<PromotionBundlePriceProfitConfDTO> profitConfOptional = profitConfDTOList.stream().filter(profitDTO -> profitDTO.getReportCode().equals(reportCode)).findFirst();
            if (profitConfOptional.isEmpty()) {
                continue;
            }
            return profitConfOptional.get().getStripTypeCode();
        }
        return null;
    }

    private List<ProfitDTO> setAuxiliaryField(List<Integer> stripTypeCodes, List<ProfitDTO> profitList) {
        Map<String, Object> map = Maps.newHashMap();
        map.put("typeCode", stripTypeCodes);
        Map<Integer, TestConfPoctStripTypeDTO> stripTypeMap = testConfPoctStripTypeRepository.list(map).stream().collect(Collectors.toMap(TestConfPoctStripTypeDTO::getTypeCode, Function.identity(), (key1, key2) -> key2));
        profitList = profitList.stream().peek(p -> {
            TestConfPoctStripTypeDTO stripType = stripTypeMap.get(p.getStripTypeCode());
            if (stripType != null) {
                p.setShowOriginPrice(stripType.getShowOriginPrice());
            }
        }).collect(Collectors.toList());

        Map<String, Object> map2 = Maps.newHashMap();
        map2.put("realStripTypeCode", stripTypeCodes);
        Map<Integer, TestReportDataConfigDTO> configMap = testReportDataConfigRepository.list(map2).stream().filter(f -> f.getReportType() == 1).collect(Collectors.toMap(TestReportDataConfigDTO::getStripTypeCode, Function.identity(), (key1, key2) -> key2));
        profitList = profitList.stream().peek(p -> {
            TestReportDataConfigDTO configDTO = configMap.get(p.getStripTypeCode());
            if (configDTO != null) {
                p.setReportCode(configDTO.getReportCode());
            }
            if(p.getStripTypeCode() != null && p.getStripTypeCode().equals(50)){
                p.setReportCode("U_MPIGM_CPNIGM_REPORT");
            }
            if(p.getStripTypeCode() != null &&  p.getStripTypeCode().equals(51)){
                p.setReportCode("U_MP_AB_CPNIGM_REPORT");
            }
            //18
            if(p.getStripTypeCode() != null &&  p.getStripTypeCode().equals(18)){
                p.setReportCode("S_CRP_SAA_REPORT");
            }
        }).collect(Collectors.toList());

        return profitList;
    }

    private List<ProfitDTO> handleProfit(List<ProfitDTO> profitList,Long testStripPriceProfitSchemeId) {
        Map<Integer, ProfitDTO> profitMap = profitList.stream().peek(p -> p.setTestPoctReportType(1)).collect(Collectors.toMap(ProfitDTO::getStripTypeCode, Function.identity(), (key1, key2) -> key2));
        log.info("处理价格方案 Map={}",profitMap);
        //5.如果存在 4,5,100 直接合成为 121
        if(profitMap.containsKey(4) && profitMap.containsKey(5) && profitMap.containsKey(100) && profitMap.get(121) != null){
            profitMap.remove(4);
            profitMap.remove(5);
            profitMap.remove(100);
        }

        //处理肺支肺衣联合检测 肺支总抗肺衣联合检测
        //存在捆绑活动
        if (profitMap.containsKey(50)) {
            if(profitMap.get(6) != null){
                profitMap.put(6,getProfitMapSetZero(profitMap.get(6)));
            }
            if(profitMap.get(17) != null){
                profitMap.put(17,getProfitMapSetZero(profitMap.get(17)));
            }
            ProfitDTO profitDTO = profitMap.get(50);
            profitDTO.setTestPoctReportType(2);
            profitMap.put(50,profitDTO);
        } else {
            //不存在捆绑活动
            if(profitMap.containsKey(6) && profitMap.containsKey(17)){
                ProfitDTO p = getProfitMapDTO("U_MPIGM_CPNIGM_REPORT");
                profitMap.put(52,p);
            }
        }
        if (profitMap.containsKey(51)) {
            if(profitMap.get(9) != null){
                profitMap.put(9,getProfitMapSetZero(profitMap.get(9)));
            }
            if(profitMap.get(17) != null){
                profitMap.put(17,getProfitMapSetZero(profitMap.get(17)));
            }
            ProfitDTO profitDTO = profitMap.get(51);
            profitDTO.setTestPoctReportType(2);
            profitMap.put(51,profitDTO);
        } else {
            if(profitMap.containsKey(9) && profitMap.containsKey(17)){
                ProfitDTO p = getProfitMapDTO("U_MP_AB_CPNIGM_REPORT");
                profitMap.put(53,p);
            }
        }
        //处理联测
        // 121 : CRP+SAA+血常规
        if (profitMap.containsKey(121)) {
            if(profitMap.get(4) != null){
                profitMap.put(4,getProfitMapSetZero(profitMap.get(4)));
            }
            if(profitMap.get(5) != null){
                profitMap.put(5,getProfitMapSetZero(profitMap.get(5)));
            }
            if(profitMap.get(100) != null){
                profitMap.put(100,getProfitMapSetZero(profitMap.get(100)));
            }
            profitMap.get(121).setTestPoctReportType(3);
            profitMap.get(121).setReportCode(StripTypeEnums.U_CRP_SAA_BLD_REPORT.getReportTypeCode());
        }
        // 18 : CRP+SAA双联试纸检测
        if(profitMap.containsKey(4) && profitMap.containsKey(5)){
            ProfitDTO p = getProfitMapDTO("U_CRP_SAA_REPORT");
            profitMap.put(54,p);
        }

        if (profitMap.containsKey(18)) {
            if(profitMap.get(4) != null){
                profitMap.put(4,getProfitMapSetZero(profitMap.get(4)));
            }
            if(profitMap.get(5) != null){
                profitMap.put(5,getProfitMapSetZero(profitMap.get(5)));
            }
        }
        //处理 14 15 联合报告
        if(profitMap.containsKey(14) && profitMap.containsKey(15)){
            ProfitDTO p = getProfitMapDTO("U_EV71IGM_CVA16IGM_REPORT");
            profitMap.put(55,p);
        }
        return Lists.newArrayList(profitMap.values());
    }

    private ProfitDTO getProfitMapDTO(String reportCode) {
        ProfitDTO p = new ProfitDTO();
        p.setSalePrice(BigDecimal.ZERO);
        p.setCityagentProfits(BigDecimal.ZERO);
        p.setClinicProfits(BigDecimal.ZERO);
        p.setCompanyagentProfits(BigDecimal.ZERO);
        p.setProvagentProfits(BigDecimal.ZERO);
        p.setYhCost(BigDecimal.ZERO);
        p.setSalesProfits(BigDecimal.ZERO);
        p.setReportCode(reportCode);
        p.setTestPoctReportType(2);
        return p;
    }

    private ProfitDTO getProfitMapSetZero(ProfitDTO p) {
        p.setSalePrice(BigDecimal.ZERO);
        p.setCityagentProfits(BigDecimal.ZERO);
        p.setClinicProfits(BigDecimal.ZERO);
        p.setCompanyagentProfits(BigDecimal.ZERO);
        p.setProvagentProfits(BigDecimal.ZERO);
        p.setYhCost(BigDecimal.ZERO);
        p.setSalesProfits(BigDecimal.ZERO);
        p.setReportCode(p.getReportCode());
        p.setTestPoctReportType(1);
        return p;
    }

    private List<PromotionBundlePriceProfitConfDTO> getPromotionBundlePriceProfitConf(Long testStripPriceProfitSchemeId) {
        PromotionBundlePriceProfitConfDTO profitConfDTO = new PromotionBundlePriceProfitConfDTO().setTestStripPriceProfitSchemeId(testStripPriceProfitSchemeId);
        return promotionBundlePriceProfitConfService.list(profitConfDTO);
    }

    private TestStripPriceProfitSchemeDTO createTestStripPriceProfitSchemeDTO(String priceProfitSchemeName,Integer isActivity) {
        //校验是否存在相同的价格方案
        TestStripPriceProfitSchemeDTO tspps = new TestStripPriceProfitSchemeDTO();
        tspps.setPriceProfitSchemeName(priceProfitSchemeName);
        if (!testStripPriceProfitSchemeService.list(tspps).isEmpty()) {
            throw new BizException(DomainBizCode.PRICE_SCHEME_NAME_ALREADY_EXISTS);
        }
        return new TestStripPriceProfitSchemeDTO().setPriceProfitSchemeName(priceProfitSchemeName)
                .setOwnerUserid((long) 1).setLevel(3).setStatus(0).setFirstAgentDisplayName("省总分成")
                .setSecondAgentDispalyName("地总分成").setThirdAgentDisplayName("业务员分成").setClinicFiledDisplayName("诊所利润")
                .setConpanyFileDisplayName("伊鸿利润").setSchemeMd5(UUID.randomUUID().toString()).setIsActivity(isActivity);
    }

    private void checkData(List<ProfitDTO> profitList) {
        profitList.forEach(r -> {
            //肺支肺衣相关
            if (r.getStripTypeCode() == 50) {
                checkData(U_MPIGM_CPNIGM_REPORT, profitList);
            }
            if (r.getStripTypeCode() == 51) {
                checkData(U_MP_AB_CPNIGM_REPORT, profitList);
            }
        });
    }

    private void checkData(Map<Integer, String> code, List<ProfitDTO> profitList) {
        code.forEach((key, value) -> {
            var profitDTO = profitList.stream().filter(i -> i.getStripTypeCode().equals(key)).findFirst().orElse(null);
            if (profitDTO == null) {
                throw new BizException(123567, "捆绑促销活动，必须配置相应单项检测价格");
            }
        });
    }

    private void bundlePriceProfitConf(ProfitDTO r, PriceProfitDTO dto) {
        //肺支肺衣相关
        if (r.getStripTypeCode() == 50) {
            createPromotionBundlePriceProfitConf(U_MPIGM_CPNIGM_REPORT, dto, c -> c.forEach(promotionBundlePriceProfitConfService::insert));
        }
        if (r.getStripTypeCode() == 51) {
            createPromotionBundlePriceProfitConf(U_MP_AB_CPNIGM_REPORT, dto, c -> c.forEach(promotionBundlePriceProfitConfService::insert));
        }
    }

    private void createPromotionBundlePriceProfitConf(Map<Integer, String> code, PriceProfitDTO dto, Consumer<List<PromotionBundlePriceProfitConfDTO>> fun) {
        List<PromotionBundlePriceProfitConfDTO> list = new ArrayList<>();
        code.forEach((key, value) -> {
            var profitDTO = dto.getProfitList().stream().filter(i -> i.getStripTypeCode().equals(key)).findFirst().orElse(null);
            var name = dto.getPriceProfitSchemeName();
            if (profitDTO == null) {
                throw new BizException(123567, "捆绑促销活动，必须配置相应单项检测价格");
            }
            list.add(new PromotionBundlePriceProfitConfDTO().setProductCombineCode(code.containsKey(50) ? "0617" : "0917")
                    .setReportCode(value).setSalePrice(profitDTO.getSalePrice())
                    .setPriceProfitSchemeName(name).setRealSalePrice(key == 50 || key == 51 ? profitDTO.getSalePrice() : new BigDecimal("0"))
                    .setStripTypeCode(key).setEffectiveStart(LocalDateTime.now()).setEffectiveEnd(LocalDateTime.now().plusYears(3))
                    .setEffectiveStatus(0).setNeedProfit(0).setTestStripPriceProfitSchemeId(dto.getTestStripPriceProfitSchemeId()));
        });
        fun.accept(list);
    }

    private TestStripPriceProfitDTO createTestStripPriceProfitDTO(Long testStripPriceProfitSchemeId, ProfitDTO r) {
        return testStripPriceProfitMapping.to(testStripPriceProfitSchemeId, r);
    }

    private void saveRecord(String operateType, Long profitId, String priceProfitSchemeName) {
        final var user = UserThreadLocal.getUser();
        testStripPriceProfitSchemeOperateRecordService.insert(new TestStripPriceProfitSchemeOperateRecordDTO().setOperater(user.getName()).setAccount(user.getMobilePhone() != null ? Long.valueOf(user.getMobilePhone()) : null).setOperateType(operateType).setProfitId(profitId).setProfitName(priceProfitSchemeName));
    }
}